package com.example.project.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.project.entity.User;
import com.example.project.result.Result;
import com.example.project.result.ResultFactory;
import com.example.project.service.IUserService;
import com.example.project.mapper.UserMapper;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/api")
public class UserApi {


    @Autowired
    IUserService userService;

    @Autowired
    UserMapper userMapper;



//    @GetMapping("/admin/user/list")
//    public Result listUsers(
//            HttpServletRequest request,
//            HttpServletResponse response,
//            @RequestParam("page")int page,
//            @RequestParam("size")int size){
//        return userService.listUsers(request,response,page,size);
//    }

    @GetMapping("/user")
    public User getUserByName(@RequestParam("userName")String userName){
        System.out.println(userName);
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUserName, userName));
        return user;
    }


    @PutMapping("/admin/user/state/{userId}")
    public Result changeUserState(@PathVariable("userId") Long userId,@RequestParam("state") int state){
        return userService.changeUserState(userId,state);
    }



    /**
     * 登录 sign-up
     *
     * 需要提交的数据
     * 1、用户账号-昵称/邮箱，
     * 2、密码
     * 3、图灵验证码
     * 4、图灵验证码的key
     * @param captcha
     * @param captchaKey
     * @param user
     * @return
     */
    @PostMapping("/user/login/{captcha}/{captcha_key}")
    public Result login(@PathVariable("captcha") String captcha,
                        @PathVariable("captcha_key") String captchaKey,
                        @RequestBody User user,
                        HttpServletRequest request,
                        HttpServletResponse response){

        return userService.doLogin(captcha,captchaKey,user,request,response);
    }

    /**
     * 退出登录
     * @return
     */
    @GetMapping("/user/logout")
    public Result logout() {
        return ResultFactory.buildSuccessResult("成功登出");
    }

    /**
     * 获取图灵验证码
     * 有效时长10分钟
     * @return
     */
    @GetMapping("/user/captcha")
    public void getCaptcha(HttpServletResponse response,@RequestParam("captcha_key")String captchaKey)  {
        try{
            userService.createCaptcha(response,captchaKey);
        }catch (Exception e){
            log.error(e.toString());
        }
    }


    /**
     * 修改密码
     * @param user
     * @return
     */
    @PutMapping("/user/password")
    public Result updatePassword( @RequestBody User user){
        return userService.updatePassword(user);
    }

    /**
     * 重置密码
     * @return
     */
    @PutMapping("/admin/user/repassword/{userId}")
    public Result reSetPassword( @PathVariable("userId") Long userId){
        return userService.reSetPassword(userId);
    }

    /**
     * 修改邮箱
     * @param user
     * @return
     */
    @PutMapping("/user/email")
    public Result updateEmail(@RequestParam("email") String email,
                              @RequestParam("verify_code") String verifyCode,
                              @RequestBody User user){
        return userService.updateEmail(email,verifyCode,user);
    }

    /**
     * 修改用户信息
     * <P>
     *     允许用户修改的内容
     *     1. 头像
     *     2. 用户名（唯一）
     *     2.5 签名
     *     3. 密码（单独修改）
     *     4. Email(唯一，单独修改)
     * </P>
     * @return
     */
    @PutMapping("/admin/user/{userId}")
    public Result updateUserInfo(HttpServletRequest request,
                                 HttpServletResponse response,
                                 @PathVariable("userId")int userId,
                                 @RequestBody User user){

        return userService.updateUserInfo(request, response, userId, user);
    }


    /**
     * 需要管理员权限
     *
     * @param userId
     * @return
     */
    @DeleteMapping("/user/{userId}")
    public Result deleteUser(HttpServletResponse response, HttpServletRequest request,
                             @PathVariable("userId") Long userId) {
        //判断当前操作的用户是谁
        //根据用户角色判断是否可以删除
        //TODO:通过注解的方式来控制权限
        return userService.deleteUserById(userId, request, response);
    }



    /**
     * 检查邮箱是否已经被注册
     *
     * @param email
     * @return SUCCESS == > 已经注册了
     *         FAIL    == > 没有注册
     */
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "当前邮箱已经被注册了"),
            @ApiResponse(responseCode = "400", description = "当前邮箱未被注册了")
    })

    @GetMapping("/user/email")
    public Result checkEmail(@RequestParam("email")String email ){
        return userService.checkEmail(email);
    }


    /**
     * 检查用户名是否已经被注册
     *
     * @param userName
     * @return SUCCESS == > 已经注册了
     *         FAIL    == > 没有注册
     */
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "当前用户名已经被注册了"),
            @ApiResponse(responseCode = "400", description = "当前用户名未被注册了")
    })

    @GetMapping("/user/user_name")
    public Result checkUserName(@RequestParam("userName")String userName ){
        return userService.checkUserName(userName);
    }


    @GetMapping("/user/check_email_code")
    public Result checkEmailCode(@RequestParam("email") String email,
                                 @RequestParam("emailCode") String emailCode){
        return userService.checkEmailCode(email,emailCode);
    }


}
